package com.caigou.service.impl;

import com.caigou.bean.cms.entity.*;
import com.caigou.bean.cms.param.*;
import com.caigou.bean.exam.entity.UserInfo;
import com.caigou.bean.exam.entity.Users;
import com.caigou.component.HtmlHomePageBuilderComponent;
import com.caigou.component.HtmlListComponent;
import com.caigou.enums.ResponseEnum;
import com.caigou.mapper.cms.*;
import com.caigou.mapper.exam.UserInfoMapper;
import com.caigou.mapper.exam.UsersMapper;
import com.caigou.service.IClientsService;
import com.caigou.util.DateUtil;
import com.caigou.util.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ClientsServiceImpl implements IClientsService {

    @Resource
    private BusinessCooperationMapper businessCooperationMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private SeekReportMapper seekReportMapper;
    @Resource
    private CmsDictionaryMapper cmsDictionaryMapper;
    @Resource
    private HtmlHomePageBuilderComponent htmlHomePageBuilderComponent;
    @Resource
    private HtmlListComponent htmlListComponent;
    @Resource
    private FeedbackMapper feedbackMapper;
    @Resource
    private UserBaseInfoMapper userBaseInfoMapper;

    @Override
    public Result<PageInfo<BusinessCooperation>> findCooperationClients(CooperationParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        PageInfo<BusinessCooperation> list = new PageInfo<>(businessCooperationMapper.findByParam(param));
        return Result.success(list);
    }

    @Override
    public Result<BusinessCooperation> findCooperationClientById(Integer id) {
        BusinessCooperation cooperation = businessCooperationMapper.selectByPrimaryKey(id);
        if (cooperation == null) {
            return Result.error(ResponseEnum.NOT_FIND_DATA);
        }
        Users user = usersMapper.findUserByUserId(cooperation.getUserId());
        if (user == null) {
            return Result.error(ResponseEnum.NO_FIND_USER);
        }
        UserInfo userInfo = userInfoMapper.findUserInfoByUserId(cooperation.getUserId());
        cooperation.setNickname(userInfo.getNickname());
        cooperation.setPhoneNumber(user.getTel());

        return Result.success(cooperation);
    }

    @Override
    public Result<Integer> saveReportClients(SaverReportParam param, String userid) {
        SeekReport cooperation = new SeekReport();
        cooperation.setProjectName(param.getProjectName());
        cooperation.setDepartmentName(param.getDepartmentName());
        cooperation.setProjectType(param.getProjectType());
        cooperation.setProjectReleaseTime(DateUtil.stringtoDate(param.getProjectReleaseTime(), "yyyy-MM-dd"));
        cooperation.setLinkman(param.getLinkman());
        cooperation.setPhoneNumber(param.getPhoneNumber());
        cooperation.setProjectUrl(param.getProjectUrl());
        cooperation.setProjectIntro(param.getProjectIntro());
        cooperation.setUpdateTime(new Date());
        cooperation.setCommitTime(new Date());
        cooperation.setHandleStatus(0);
        cooperation.setUserid(userid);
        cooperation.setPicUrl(param.getPicUrl());
        int selective = seekReportMapper.insertSelective(cooperation);
        if (selective == 0) {
            return Result.error(ResponseEnum.COMMIT_ERROR);
        }
        return Result.success(selective);
    }

    @Override
    public Result<Integer> handelReportClients(SaveCooperationParam param, String userId) {
        //一期不做处理
        UserBaseInfo userBaseInfo = userBaseInfoMapper.findUserBaseInfoByUserId(userId);
        if (userBaseInfo == null) {
            return Result.error(ResponseEnum.NO_FIND_STAFF);
        }
        SeekReport seekReport = new SeekReport();
        seekReport.setId(param.getId());
        seekReport.setHandler(userBaseInfo.getRealName());
        seekReport.setHandleStatus(param.getHandleStatus());
        seekReport.setHandleTime(new Date());
        seekReport.setUpdateTime(new Date());
        seekReport.setHandlerUserId(userId);
        seekReport.setRemarks(param.getRemarks());
        int update = seekReportMapper.updateByPrimaryKeySelective(seekReport);
        if (update == 0) {
            return Result.error(ResponseEnum.COMMIT_ERROR);
        }
        return Result.success(update);
    }

    @Override
    public Result<PageInfo<SeekReport>> queryReportClients(SeekReportParam param) {
        List<UserInfo> userInfos = null;
        if (!StringUtils.isEmpty(param.getCommitUser())) {
            userInfos = userInfoMapper.findUserInfoByNickname(param.getCommitUser());
            List<String> userIds;
            if (CollectionUtils.isEmpty(userInfos)) {
                userIds = userInfos.stream().map(UserInfo::getUserid).distinct().collect(Collectors.toList());
                param.setUserIds(userIds);
            }
        }

        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        PageInfo<SeekReport> list = new PageInfo<>(seekReportMapper.findByParam(param));
        if (!CollectionUtils.isEmpty(list.getList())) {
            List<String> userIds = list.getList().stream().map(SeekReport::getUserid).collect(Collectors.toList());
            List<UserInfo> infoByUserIds = userInfoMapper.findUserInfoByUserIds(userIds);
            if (!CollectionUtils.isEmpty(infoByUserIds)) {
                Map<String, String> userIdNicknameMap = infoByUserIds.stream().collect(Collectors.toMap(UserInfo::getUserid, UserInfo::getNickname));
                list.setList(list.getList().stream().peek(bean -> bean.setCommitUser(userIdNicknameMap.get(bean.getUserid()))).collect(Collectors.toList()));
            }
        }
        return Result.success(list);
    }

    @Override
    public Result<SeekReport> queryReportClient(Integer id) {
        SeekReport seekReport = seekReportMapper.selectByPrimaryKey(id);
        Users user = usersMapper.findUserByUserId(seekReport.getUserid());
        if (user == null) {
            return Result.error(ResponseEnum.NO_FIND_USER);
        }
        UserInfo userInfo = userInfoMapper.findUserInfoByUserId(seekReport.getUserid());
        seekReport.setUserid("");
        seekReport.setNickname(userInfo.getNickname());
        seekReport.setCommitUser(user.getTel());
        return Result.success(seekReport);
    }

    @Override
    public Result<List<CmsDictionary>> findIndustryDic() {
        List<CmsDictionary> industryDic = cmsDictionaryMapper.findAllIndustryDic();

        return Result.success(industryDic);
    }

    @Override
    public Result testPicSpecial() {
        String s = htmlListComponent.buildNewsSpecialList();
        return Result.success(s);
    }

    @Override
    public Result<List<CmsDictionary>> findProjectDic() {
        List<CmsDictionary> industryDic = cmsDictionaryMapper.findAllProjectDic();

        return Result.success(industryDic);
    }

    @Override
    public Result<Integer> saveFeedback(FeedbackParam param, String userid) {
        Feedback feedback = new Feedback();
        feedback.setBriefIntro(param.getBriefIntro());
        feedback.setArticleId(param.getArticleId());
        feedback.setContactInformation(param.getContactInformation());
        feedback.setFeedbackType(param.getFeedbackType());
        feedback.setCreateTime(new Date());
        feedback.setUserid(userid);
        feedback.setHandlingStatus(0);
        int insertNum = feedbackMapper.insertSelective(feedback);
        return Result.success(insertNum);
    }

    @Override
    public Result<List<CmsDictionary>> findFeedbackType() {
        List<CmsDictionary> feedbackDic = cmsDictionaryMapper.findAllFeedbackTypeDic();
        return Result.success(feedbackDic);
    }

    @Override
    public Result<PageInfo<Feedback>> findFeedbackList(FeedbackParam param) {
        if (!StringUtils.isEmpty(param.getPhoneNumber())) {
            Users user = usersMapper.findUserByTel(param.getPhoneNumber());
            if (user != null) {
                param.setUserid(user.getUserid());
            } else {
                param.setUserid("-1");
            }
        }
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        PageInfo<Feedback> list = new PageInfo<>(feedbackMapper.findFeedbackListByParam(param));
        if (!CollectionUtils.isEmpty(list.getList())) {
            List<String> userIds = list.getList().stream().map(Feedback::getUserid).distinct().collect(Collectors.toList());
            List<Users> users = usersMapper.findUsersByUserIds(userIds);
            if (!CollectionUtils.isEmpty(users)) {
                Map<String, String> userIdTelMap = users.stream().collect(Collectors.toMap(Users::getUserid, Users::getTel));
                list.getList().forEach(bean -> {
                    bean.setSubmitUser(userIdTelMap.get(bean.getUserid()));
                });

            }


        }

        return Result.success(list);
    }

    @Override
    public Result<Feedback> findFeedbackDetail(FeedbackParam param) {
        Feedback feedback = feedbackMapper.selectByPrimaryKey(param.getId());
        if (feedback != null) {
            Users users = usersMapper.findUserByUserId(feedback.getUserid());
            if (users != null) {
                feedback.setSubmitUser(users.getTel());
            }
            UserInfo userInfo = userInfoMapper.findUserInfoByUserId(feedback.getUserid());
            if (userInfo != null) {
                feedback.setSubmitNickName(userInfo.getNickname());
            }
        }
        return Result.success(feedback);
    }

    @Override
    public Result<Integer> batchFeedbackDealWith(List<Integer> ids, String userid) {
        if (!CollectionUtils.isEmpty(ids)) {
            UserBaseInfo userBaseInfo = userBaseInfoMapper.findUserBaseInfoByUserId(userid);
            if (userBaseInfo == null) {
                return Result.error(ResponseEnum.NO_FIND_STAFF);
            }
            ids.forEach(id -> {
                Feedback feedback = new Feedback();
                feedback.setId(id);
                feedback.setHandlingStatus(1);
                feedback.setHandlingUser(userBaseInfo.getRealName());
                feedback.setHandlingTime(new Date());
                int updateNum = feedbackMapper.updateByPrimaryKeySelective(feedback);
            });

        }
        return Result.success(ids.size());
    }

    @Override
    public Result<Integer> feedbackDealWith(FeedbackParam param, String userid) {
        Feedback feedback = feedbackMapper.selectByPrimaryKey(param.getId());
        if (feedback == null) {
            return Result.error(ResponseEnum.NO_FEEDBACK_DETAIL);
        }
        UserBaseInfo userBaseInfo = userBaseInfoMapper.findUserBaseInfoByUserId(userid);
        if (userBaseInfo == null) {
            return Result.error(ResponseEnum.NO_FIND_STAFF);
        }
        Feedback updateFeedback = new Feedback();
        BeanUtils.copyProperties(feedback, updateFeedback);
        updateFeedback.setHandlingStatus(param.getHandlingStatus());
        updateFeedback.setHandlingUser(userBaseInfo.getRealName());
        updateFeedback.setRemarks(param.getRemarks());
        updateFeedback.setHandlingUserId(userBaseInfo.getUserid());
        updateFeedback.setHandlingTime(new Date());
        int updateNum = feedbackMapper.updateByPrimaryKeySelective(updateFeedback);
        return Result.success(updateNum);
    }

    @Override
    public Result<Integer> saveCooperationClients(SaveCooperationParam param, String userId) {
        BusinessCooperation cooperation = new BusinessCooperation();
        cooperation.setSupplierName(param.getSupplierName());
        cooperation.setIndustry(param.getIndustry());
        cooperation.setLinkman(param.getLinkman());
        cooperation.setPosition(param.getPosition());
        cooperation.setContactWay(param.getContactWay());
        cooperation.setIntention(param.getIntention());
        cooperation.setUpdateTime(new Date());
        cooperation.setCommitTime(new Date());
        cooperation.setUserId(userId);
        cooperation.setPicUrl(param.getPicUrl());
        cooperation.setHandleStatus(0);
        int selective = businessCooperationMapper.insertSelective(cooperation);
        if (selective == 0) {
            return Result.error(ResponseEnum.COMMIT_ERROR);
        }
        return Result.success(selective);

    }

    @Override
    public Result<Integer> handelCooperationClients(SaveCooperationParam param, String userId) {
        UserBaseInfo userBaseInfo = userBaseInfoMapper.findUserBaseInfoByUserId(userId);
        if (userBaseInfo == null) {
            return Result.error(ResponseEnum.NO_FIND_STAFF);
        }
        BusinessCooperation cooperation = new BusinessCooperation();
        cooperation.setId(param.getId());
        cooperation.setHandler(userBaseInfo.getRealName());
        cooperation.setHandleStatus(param.getHandleStatus());
        cooperation.setHandleTime(new Date());
        cooperation.setUpdateTime(new Date());
        cooperation.setHandlerUserId(userId);
        cooperation.setRemarks(param.getRemarks());
        int update = businessCooperationMapper.updateByPrimaryKeySelective(cooperation);
        if (update == 0) {
            return Result.error(ResponseEnum.COMMIT_ERROR);
        }
        return Result.success(update);
    }

    public int getCooperationCountByHandleStatus(int handleStatus){
        return businessCooperationMapper.getCountByHandleStatus(handleStatus);
    }

    public int getReportCountByHandleStatus(int handleStatus){
        return seekReportMapper.getCountByHandleStatus(handleStatus);
    }

    public int getFeedbackCountByHandleStatus(int handleStatus){
        return feedbackMapper.getCountByHandleStatus(handleStatus);
    }
}
